package com.topvision.face;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;

import java.util.ArrayList;

/**
 * 用于检测手机摇晃
 *
 * @author 郑智仁
 * @see <a href="http://blog.csdn.net/zhengzhiren" mce_href="http://blog.csdn.net/zhengzhiren">Blog</a>
 */
public class ShakeDetector implements SensorEventListener {
    /**
     * 检测的时间间隔
     */
    static final int UPDATE_INTERVAL = 100;
    /**
     * 上一次检测的时间
     */
    long mLastUpdateTime;
    /**
     * 上一次检测时，加速度在x、y、z方向上的分量，用于和当前加速度比较求差。
     */
    float mLastX, mLastY, mLastZ;
    Context mContext;
    SensorManager mSensorManager;
    ArrayList<OnShakeListener> mListeners;
    /**
     * 摇晃检测阈值，决定了对摇晃的敏感程度，越小越敏感。
     */
    public int shakeThreshold = 30;

    public ShakeDetector(Context context) {
        mContext = context;
        mSensorManager = (SensorManager) context
                .getSystemService(Context.SENSOR_SERVICE);
        mListeners = new ArrayList<OnShakeListener>();
    }

    /**
     * 当摇晃事件发生时，接收通知
     */
    public interface OnShakeListener {
        /**
         * 当手机摇晃时被调用
         */
        void onShake();

        /**
         * 当手机不摇晃时调用
         */
        void onNotShake();
    }

    /**
     * 注册OnShakeListener，当摇晃时接收通知
     *
     * @param listener
     */
    public void registerOnShakeListener(OnShakeListener listener) {
        if (mListeners.contains(listener))
            return;
        mListeners.add(listener);
    }

    /**
     * 移除已经注册的OnShakeListener
     *
     * @param listener
     */
    public void unregisterOnShakeListener(OnShakeListener listener) {
        mListeners.remove(listener);
    }

    /**
     * 启动摇晃检测
     */
    public void start() {
        if (mSensorManager == null) {
            throw new UnsupportedOperationException();
        }
        Sensor sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        if (sensor == null) {
            throw new UnsupportedOperationException();
        }
        boolean success = mSensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_GAME);
        if (!success) {
            throw new UnsupportedOperationException();
        }
    }

    /**
     * 停止摇晃检测
     */
    public void stop() {
        if (mSensorManager != null)
            mSensorManager.unregisterListener(this);
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        long currentTime = System.currentTimeMillis();
        long diffTime = currentTime - mLastUpdateTime;
        if (diffTime < UPDATE_INTERVAL)
            return;
        mLastUpdateTime = currentTime;
        float x = event.values[0];//x轴方向的重力加速度，向右为正
        float y = event.values[1];//y轴方向的重力加速度，向前为正
        float z = event.values[2];//z轴方向的重力加速度，向上为正
        float deltaX = x - mLastX;
        float deltaY = y - mLastY;
        float deltaZ = z - mLastZ;
        mLastX = x;
        mLastY = y;
        mLastZ = z;
        float delta = (float) (Math.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ) / diffTime * 10000);
        if (delta > shakeThreshold) { // 当加速度的差值大于指定的阈值，认为这是一个摇晃
            Log.i("Shake", "...." + delta);
            this.notifyListeners(true);
        } else {
            this.notifyListeners(false);
            //判断为静止，可以进行人脸检测
        }
    }

	/*public void onSensorChanged(SensorEvent event){    
        if(event.sensor == null){
			return;  
		}  
//		mIsSmartStayOn= Settings.System.getInt(cr,"isSmartStayEnabled",0) == 1 ? true : false;//人眼识别打开时才启动重力监听
//		if(mIsSmartStayOn == true){
//			Log.i(TAG,"gsensor respond");
			float[] curGravity = new float[3];
			curGravity[0] = (float)firFilter1.filter1((double)event.values[0]);
			curGravity[1] = (float)firFilter2.filter1((double)event.values[1]);
			curGravity[2] = (float)firFilter3.filter1((double)event.values[2]);
			curGravity = filter1.SMAFilter(curGravity);		//取得三轴重力数据并滤波处理
			
			if(mAccSkipCnt < __ACC_SKIP_SAMPLES) {
				mAccSkipCnt++;
				return ;					//待gsensor读数稳定才继续后面的处理
			}

			float[] linearAcc = new float[]{
					event.values[0]-curGravity[0],
					event.values[1]-curGravity[1],
					event.values[2]-curGravity[2]
			};
			double linearLen = KonkaGeneHelper.vecLength(linearAcc);	//三轴数据平方和相加开根号的结果
			Log.w(TAG,"linearLen is "+linearLen);
			if(linearLen < 0.6f && DeviceFlating == false){	//如果手机一开始没有静止并且linearLen小于0.6
				DeviceFlating = true;			//手机趋近于静止状态（不论方向）
			}
			if(linearLen > 1.0f && DeviceFlating == true && pm.isScreenOn() == true){
				DisplayEyeIcon(1);			//如果手机静止的，并且gsensor检测到linearLen大于1且手机亮屏					freshDetect();
				DeviceFlating = false;		//马上启动人眼识别
			}			
//		}		
	}*/

    /**
     * 当摇晃事件发生时，通知所有的listener
     */
    private void notifyListeners(boolean isShaked) {
        for (OnShakeListener listener : mListeners) {
            if (isShaked) {
                listener.onShake();
            } else {
                listener.onNotShake();
            }
        }
    }
}